import { SYSTEM_DETAIL_ROUTE } from '@/router';
import { System, useSystemRepository } from '@/store/system-repository';
import { guid, traverseTree } from '@/util';
import { RouteRecordNameGeneric } from 'vue-router';

export function useSystemService() {
  const systemRepository = useSystemRepository();

  const systemDetailPages = computed(() => {
    const projectDetailPages_ = new Set();
    traverseTree(
      node => {
        projectDetailPages_.add(node.name);
      },
      [SYSTEM_DETAIL_ROUTE],
    );
    return projectDetailPages_;
  });

  const addOrEditSystem = (system: System): Promise<void> => {
    if (system.id) {
      // TODO 编辑
    } else {
      systemRepository.addSystem({ ...system, id: guid() });
    }
    return new Promise(resolve => {
      resolve();
    });
  };

  const getIsSystemDetail = (routeName: RouteRecordNameGeneric): boolean => {
    return systemDetailPages.value.has(routeName as string);
  };

  const system = (systemId: string): Promise<System | undefined> => {
    return new Promise(resolve => {
      resolve(systemRepository.getSystem(systemId));
    });
  };

  return { systemDetailPages, system, addOrEditSystem, getIsSystemDetail };
}
